<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Cate extends Model
{
    // 关联的数据表
    public $table = 'category';

    // 数据表主键
    public $key = 'id';

    // 允许批量操作的字段
    public $guarded = [];

    // 是否维护create_at、update_at字段
    public $timestamps = false;

    public function tree()
	{
	    $cates = $this->orderBy('cate_order','asc')->get();
	    return $this->getTree($cates);
	}

	public function getTree($data,$pid=0)
	{
	    $arr = [];
        foreach ($data as $k => $v) {
             # code...
             if ($v->cate_pid == $pid) {
                # code...
                $v->cate_name = $v->cate_name;
                $arr[] = $v;
                foreach ($data as $m => $n) {
                    # code...
                    if ($v->id == $n->cate_pid) {
                        # code...
                        $n->cate_name = '|-----'.$n->cate_name;
                        $arr[] = $n;
                    }
                }
            }
        }
	    return $arr;
	}

    public function article()
    {
        # code...
        return $this->hasMany('App\Model\Article','cate_id','id');
    }
}
